package com.fly.simple;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MainRun
{
    private static String uploadUrl = "http://124.71.129.204:8083/post";
    
    private static File file;
    
    /**
     * 静态初始化代码块实现：jar运行时从内部拷贝上传文件到当前目录，方便后续构造请求
     */
    static
    {
        String protocol = MainRun.class.getResource("").getProtocol();
        log.info("protocol: {}", protocol);
        if ("jar".equals(protocol))
        {
            try (InputStream is = MainRun.class.getResourceAsStream("/data/nginx-1.25.3.tar.gz"))
            {
                file = new File("nginx-1.25.3.tar.gz");
                FileUtils.copyInputStreamToFile(is, file);
                log.info("{}", file.getCanonicalPath());
            }
            catch (IOException e)
            {
                log.error(e.getMessage(), e);
            }
        }
        else
        {
            String path = MainRun.class.getResource("/data/nginx-1.25.3.tar.gz").getPath();
            log.info("{}", path);
            file = new File(path);
        }
    }
    
    /**
     * 线程池保证程序一直运行
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        log.info("################################################################################################");
        log.info("to start please run: java -jar unirest-show-0.0.1.jar --server.url=http://124.71.129.204:8083/post");
        log.info("################################################################################################");
        if (args.length > 0)
        {
            // 支持命令行指定上传接口
            String url = Stream.of(args).filter(arg -> arg.contains("--server.url")).map(arg -> StringUtils.substringAfter(arg, "=")).collect(Collectors.joining());
            if (StringUtils.isNotBlank(url))
            {
                log.info("server.url={}", url);
                uploadUrl = url;
            }
        }
        long delay = 60000L - System.currentTimeMillis() % 60000L - 1; // 计算延迟（微调1ms），保证准时启动
        log.info("initialDelay {} Seconds", delay / 1000.0);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> {
            post();
        }, delay, 60000L, TimeUnit.MILLISECONDS);
    }
    
    /**
     * Unirest发送post请求<br>
     * https://kong.github.io/unirest-java/#requests
     */
    private static void post()
    {
        try
        {
            log.info("Unirest start");
            HttpResponse<JsonNode> jsonResponse = Unirest.post(uploadUrl)
                .header("accept", "application/json")
                .field("id", System.currentTimeMillis() % 1000)
                .field("file", file) // 文件
                .asJson();
            log.info("###### Response status：{}", jsonResponse.getStatus());
        }
        catch (UnirestException e)
        {
            log.error(e.getMessage(), e);
        }
    }
}
